import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_tbox.dart';
import 'package:inmotion_pro/http/area_helper.dart';
import 'package:inmotion_pro/pages/main/helper.dart';
import 'package:inmotion_pro/pages/mixin/bluetooth_mixin.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/mixin/check_mixin.dart';
import 'package:inmotion_pro/pages/others/common_enum/tbox_status_type.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:inmotion_pro/service/web_socket_service.dart';

import 'state.dart';

// App底部导航栏控制器
class RootController extends GetxController
    with CheckMixin, CacheMixin, BluetoothMixin {
  // 状态
  final RootState state = RootState();

  // 监听currentUserArea变化
  StreamSubscription<String>? _currentUserAreaSubscription;

  // 监听currentVehicleBleName变化
  StreamSubscription<String>? _currentVehicleBleNameSubscription;

  // 监听isCurrentVehicleOwner变化
  StreamSubscription<bool?>? _isCurrentVehicleOwnerSubscription;

  // 防抖定时器
  Timer? _debounceTimer;

  // mainHelper实例
  MainHelper get mainHelper => MainHelper();

  void currentPageChanged(int index) {
    state.currentIndex.value = index;
  }

  @override
  void onInit() {
    super.onInit();

    // 监听当前用户区域变化
    _listenCurrentUserArea();
    // 监听当前车辆BleName变化 & 车主状态变化，开始轮询云盒在线状态
    _listenCurrentVehicleForTboxStatusAndOwner();
    // 获取用户所属地区
    mainHelper.setBaseUrlByArea();
    // 启动云盒在线状态轮询任务
    _startGetTboxStatusPolling();
  }

  // 监听当前用户区域变化
  _listenCurrentUserArea() {
    _currentUserAreaSubscription =
        GlobalService.to.currentUserArea.listen((area) {
      if (isCurrentUidValid) {
        debugPrint("✅ 当前用户区域：$area");
        // 建立WebSocket连接
        WebSocketService.to.disconnect();
        WebSocketService.to.connect(AreaHelper.wssUrl);
      }
    });
    // 初始化时设置当前用户区域
    GlobalService.to.currentUserArea.value = AreaHelper.httpArea;
  }

  // 监听当前车辆BleName变化 & 车主状态变化，开始轮询云盒在线状态
  _listenCurrentVehicleForTboxStatusAndOwner() {
    // 监听当前车辆BleName变化
    _currentVehicleBleNameSubscription =
        GlobalService.to.currentVehicleBleName.listen((bleName) {
      _startGetTboxStatusPolling();
    });
    // 监听当前车辆车主状态变化
    _isCurrentVehicleOwnerSubscription =
        GlobalService.to.isCurrentVehicleOwner.listen((isOwner) {
      _startGetTboxStatusPolling();
    });
  }

  // 开始轮询云盒在线状态【刷新条件：车主状态变化、当前车辆BleName变化】
  _startGetTboxStatusPolling() {
    // 取消之前的定时器
    _debounceTimer?.cancel();
    // 设置新的定时器，300ms防抖
    _debounceTimer = Timer(const Duration(milliseconds: 300), () {
      debugPrint("✅ 触发云盒在线状态轮询任务刷新");
      // 当本地缓存车辆，未经过车主认证时，会执行
      _refreshTBoxSupportStatus();
      // 当为车主且车辆支持云盒时，会执行
      mainHelper.toggleTboxOnlineStatusPollingTask();
    });
  }

  // 刷新云盒支持状态
  _refreshTBoxSupportStatus() {
    if (!isCurrentUidValid) return;
    final vehicleModel = GlobalService.to.currentVehicleModel.value;
    // 只有当前缓存车辆，缓存中的数据不支持云盒，才需要检查云盒支持状态
    if (vehicleModel.tboxStatus.value != TBoxStatus.none) {
      return;
    }
    // 获取云盒状态
    ApiHelper()
        .checkTboxSupport(vehicleModel.sn, vehicleModel.productModel)
        .then((isSupport) {
      if (isSupport) {
        debugPrint("✅ 当前车辆【支持云盒】");
        return cacheMixinUpdateCacheVehicle(
          vehicleModel.bleName,
          tboxStatus: TBoxStatus.offline.rawValue,
        );
      } else {
        debugPrint("✅ 当前车辆【不支持云盒】");
        return Future(() => isSupport);
      }
    }).catchErrorHandler();
  }

  @override
  void onClose() {
    super.onClose();
    _currentUserAreaSubscription?.cancel();
    _currentUserAreaSubscription = null;
    _currentVehicleBleNameSubscription?.cancel();
    _currentVehicleBleNameSubscription = null;
    _isCurrentVehicleOwnerSubscription?.cancel();
    _isCurrentVehicleOwnerSubscription = null;
  }
}
